package com.controller.lyxmcontroller.controller.behind;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aliyun.oss.OSSClient;
import com.controller.lyxmcontroller.config.OSSClientConstants;
import com.controller.lyxmcontroller.util.AliyunOSSClientUtil;
import com.service.lyxmserviceapi.model.Author;
import com.service.lyxmserviceapi.model.Module;
import com.service.lyxmserviceapi.service.behind.BehindService;
import com.service.lyxmserviceapi.service.index.IndexService;
import com.service.lyxmserviceapi.service.module.ModuleService;


@Controller
public class BehindArticleController {
	@Autowired
	private ModuleService moduleServiceImpl;
	@Autowired
	private IndexService indexServiceImpl;
	@Autowired
	private BehindService behindDaoImpl;

	@GetMapping("/login/beforeGetArticle")
	public String beforeGetArticle(Model model){
		//获取模块信息
		//获取首页模块列表
		List<Module> moduleList = moduleServiceImpl.getModuleListBehind();
		model.addAttribute("moduleList",moduleList);
		//获取作者信息 用的首页的
		List<Author> authorList = indexServiceImpl.getAuthorList();
		model.addAttribute("authorList", authorList);
		
		//获取首页主模块列表  只显示主木块
		List<Module> moduleList1 = moduleServiceImpl.getMainModuleListBehind();
		model.addAttribute("moduleList1",moduleList1);
		
		
		
		return "/behind/insertArticle";
	}
	
	@PostMapping("/pictrueUpload")
	@ResponseBody
	public String pictureUpload(HttpServletRequest request,HttpServletResponse response,Map<String, Object> model){
		
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map对象
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String targetpath = "static/img/linshi/";
        String  fileName ="";
        File wenjianjia = new File(path+targetpath);
        if(!wenjianjia.exists()){
        	wenjianjia.mkdir();
        }
        File tagetFile =null;
        long times = 0;
        for(MultipartFile file1 :files.values()){
            fileName=file1.getOriginalFilename();//相片的名字
            times = new Date().getTime();
            tagetFile = new File(path+targetpath+String.valueOf(times)+fileName);
            if(!tagetFile.exists()){//文件名不存在 则新建文件，并将文件复制到新建文件中
                try {
                    tagetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                	file1.transferTo(tagetFile);//到这里就可以上传了，以下是处理图片及允许gif的上传
                	
                  //图片扩展名
                    String types=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{    
            	times = new Date().getTime();
            	tagetFile = new File(path+targetpath+String.valueOf(times)+fileName);
            	 try {
                     tagetFile.createNewFile();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 try {
                 	file1.transferTo(tagetFile);//到这里就可以上传了，以下是处理图片及允许gif的上传
                 	
                   //图片扩展名
                     String types=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                 } catch (IllegalStateException e) {
                     e.printStackTrace();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
            }
        }
        OSSClient ossClient = new OSSClient(OSSClientConstants.ENDPOINT, OSSClientConstants.ACCESS_KEY_ID, OSSClientConstants.ACCESS_KEY_SECRET);
        String name = AliyunOSSClientUtil.uploadObject2OSS(ossClient, tagetFile, OSSClientConstants.BACKET_NAME, OSSClientConstants.FOLDER);
        String url = OSSClientConstants.BACKET_NAME+"."+OSSClientConstants.ENDPOINT+"/"+OSSClientConstants.FOLDER+tagetFile.getName();
        
        String a = "{\"aaa\":\"https://"+url+"\"}";
        JSONObject json = JSONObject.fromObject(a);  
		return json.toString();
	}
	
	@PostMapping("/insertArticle")
	@ResponseBody
	public String insertArticle(String title,String context,String authorId,String moduleId,String description,
			String imgsrc,String target, Map<String, Object> model){
		
		try{
			Integer result = behindDaoImpl.insertArticle(title, context, authorId, moduleId, description, imgsrc, target);
			String a = "";
			if(result==1){
				a = "{\"result\":\"插入成功\"}";
	        }else{
	        	a = "{\"result\":\"插入失败\"}";
	        }
	        JSONObject json = JSONObject.fromObject(a);  
			return json.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "{\"result\":\"插入失败\"}";
		
	}
	
	
	/**
	 * 新增模块
	 * @param title
	 * @param context
	 * @param authorId
	 * @param moduleId
	 * @param description
	 * @param imgsrc
	 * @param target
	 * @param model
	 * @return
	 */
	@PostMapping("/insertModule")
	@ResponseBody
	public String insertModule(String moduleName,String belongModuleId){
		
		try{
			Integer result = behindDaoImpl.insertModule(moduleName, belongModuleId);
			String a = "";
			if(result==1){
				a = "{\"result\":\"插入成功\"}";
	        }else{
	        	a = "{\"result\":\"插入失败\"}";
	        }
	        JSONObject json = JSONObject.fromObject(a);  
			return json.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "{\"result\":\"插入失败\"}";
	}
	
	
	@GetMapping("/beforeAuthor")
	public String beforInsertAuthor(){
		
		return "/behind/insertAuthor";
	}
	
	/**
	 * 新增模块
	 * @param title
	 * @param context
	 * @param authorId
	 * @param moduleId
	 * @param description
	 * @param imgsrc
	 * @param target
	 * @param model
	 * @return
	 */
	@PostMapping("/insertAuthor")
	@ResponseBody
	public String insertAuthor(String authorName,String realName,String introduction,String imgsrc){
		
		try{
			Integer result = behindDaoImpl.insertAuthor(authorName, realName, introduction, imgsrc);
			String a = "";
			if(result==1){
				a = "{\"result\":\"插入成功\"}";
	        }else{
	        	a = "{\"result\":\"插入失败\"}";
	        }
	        JSONObject json = JSONObject.fromObject(a);  
			return json.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "{\"result\":\"插入失败\"}";
	}
	
}
